<template>
  <div>
    <el-tree
      ref="treeRef"
      :data="list"
      node-key="id"
      :props="{label:'name'}"
      :show-checkbox="true"
      :check-strictly="true"
      :default-expand-all="true"
    />
    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="hsubmit">确定</el-button>
      <el-button @click="hcanle">取消</el-button>
    </div>
  </div>
</template>
<script>
import { tranList } from '@/utils'
import { getPermissionList } from '@/api/permissions'
import { getRoleDetail, assignPerm } from '@/api/settings'
export default {
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.loadPermissionList()
  },
  methods: {
    // 获得当前角色权限详情
    async loadoleDetail() {
      try {
        const res = await getRoleDetail(this.roleId)
        this.$refs.treeRef.setCheckedKeys(res.data.permIds)
        console.log(res, '权限详情')
      } catch (error) {
        console.log(error)
      }
    },
    // 权限树状分层函数
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        console.log(res)
        this.list = tranList(res.data)
        // 触发权限详情
        this.loadoleDetail()
      } catch (error) {
        console.log(error)
      }
    },
    async hsubmit() {
      // 获得已经选中的权限
      const permIds = this.$refs.treeRef.getCheckedKeys()
      try {
        // 修改角色权限
        await assignPerm({ id: this.roleId, permIds: permIds })
      } catch (error) {
        console.log(error)
      }
      this.$emit('close')
    },
    hcanle() {
      this.$emit('close')
    }
  }
}
</script>
